#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import time
from traceback import format_exc
import re
import urllib2
import urllib

from util.logger import error_log, process_log
from util.app_global import headers, client_service_url_prefix, upgrade_url


def singleton(cls, *args, **kw):
    instances = {}

    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton


class ServiceException(Exception):
    pass


class ClientService:
    """
    ClientService交互模块
    """
    url_prefix = client_service_url_prefix
    upgrade_url = upgrade_url

    def __init__(self):
        pass

    @staticmethod
    def _request(url, payload=None, param=None):
        """

        Args:
            url:
            payload:
            param:

        Returns:

        """
        if not param:
            param = {}
        try_count = 0
        res = None
        while True:
            try:
                params = urllib.urlencode(param)
                _url = "%s?%s" % (url, params)
                process_log().info(_url)
                request = urllib2.Request(url=_url, headers=headers)
                res = urllib2.urlopen(request).read()
                break
            except (IOError, ValueError), e:
                try_count += 1
                process_log().info('can not connect to server, retry ... | reason: %s' % str(e))
                time.sleep(5)
                if try_count == 5:
                    error_log().error(format_exc())
                    raise e
        return res

    def changelog(self, current_version, best_version):
        url = '%s' % self.upgrade_url
        try:
            res = self._request(url)
        except Exception, e:
            error_log().error(str(e))
            return None
        changelog_files = re.findall('(?<=href=")(.*changelog.*)(?=">)', res)
        version = {}
        for _file in changelog_files:
            version[re.findall('\d.\d.\d', _file)[0]] = _file
        _min = int(current_version.replace('.', ''))
        _max = int(best_version.replace('.', ''))
        changelogs = filter(lambda x: _max >= int(x.replace('.', '')) > _min, version.keys())
        result = []
        for ver in changelogs:
            res = self._request('%s/%s' % (url, version[ver]))
            result.append(json.loads(res))
        return result


if __name__ == '__main__':
    print ClientService().changelog('0.2.1', '1.1.1')
